/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxinline.manager.utilitario;

import br.com.foxinline.modelo.Anexo;
import br.com.foxinline.modelo.Bairro;
import br.com.foxinline.modelo.Endereco;
import br.com.foxinline.modelo.Imovel;
import br.com.foxinline.modelo.Proprietario;
import br.com.foxinline.servico.AnexoServico;
import br.com.foxinline.servico.EnderecoServico;
import br.com.foxinline.servico.ImovelServico;
import br.com.foxinline.servico.ProprietarioServico;
import br.com.foxinline.util.ArquivoUtilitario;
import br.com.foxinline.util.Campo;
import br.com.foxinline.util.ImovelMerge;
import br.com.foxinline.util.MergeUtilitario;
import br.com.foxinline.util.Msg;
import br.com.foxinline.util.ProprietarioMerge;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author nayra
 */
@ViewScoped
@ManagedBean
public class ManagerAtualizarImovel {

    @EJB
    private ImovelServico imovelServico;
    @EJB
    private ProprietarioServico proprietarioServico;
    @EJB
    private EnderecoServico enderecoServico;
    @EJB
    private AnexoServico anexoServico;
    private ImovelMerge imovelMerge;
    private ArquivoUtilitario arquivoUtilitario;
    private String inscImovel;

    @PostConstruct
    public void init() {
        this.arquivoUtilitario = new ArquivoUtilitario();
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        Imovel imA = new Imovel();
        Imovel imI = new Imovel();
        if (params.containsKey("idImovelAlt")) {
            String idImovelAlteracao = params.get("idImovelAlt");
            imA = imovelServico.find(Long.parseLong(idImovelAlteracao));
            this.inscImovel = inscricaoCadastral(imA);
            imI = imovelServico.findImovelInscCadastral(this.inscImovel).get(0);
            this.imovelMerge = new ImovelMerge(imI, imA);
        } else if (this.imovelMerge != null && this.imovelMerge.getImInclusao().getId() != null) {
            imI = this.imovelServico.find(this.imovelMerge.getImInclusao().getId());
            imA = this.imovelServico.find(this.imovelMerge.getImAlteracao().getId());
            this.imovelMerge = new ImovelMerge(imI, imA);
        } else {
            this.imovelMerge = new ImovelMerge(imI, imA);
        }

    }

    public void atualizar() {

        try {
            this.imovelMerge.getImInclusao().setGroupUpdate(this.imovelMerge.getImAlteracao().getGroupUpdate());

            //Campos Imovel
            for (Campo<?> campo : this.imovelMerge.getCampos()) {
                if (campo.getUsarAlteracao()) {
                    MergeUtilitario.setPrivateField(this.imovelMerge.getImInclusao(), campo.getField(), campo.getVlrAlteracao());
                }
            }

            //Endereco Imóvel
            if (this.imovelMerge.getEnderecoIncluido() != null && this.imovelMerge.getUsarEnderecoIncluido()) {
                Endereco e = this.imovelMerge.getEnderecoIncluido().getClone();
                e.setId(null);
                e = (Endereco) MergeUtilitario.setCamposNulos(e);
                e.setImovel(this.imovelMerge.getImInclusao());
                this.enderecoServico.save(e);
                this.imovelMerge.getImInclusao().setEnderecoImovel(e);
            } else if (this.imovelMerge.getcEndereco() != null) {
                //Campos Endereco imóvel
                for (Campo<?> campo : this.imovelMerge.getcEndereco()) {
                    if (campo.getUsarAlteracao()) {
                        MergeUtilitario.setPrivateField(this.imovelMerge.getImInclusao().getEnderecoImovel(), campo.getField(), campo.getVlrAlteracao());
                    }
                }
            }
            if (this.imovelMerge.getImAlteracao().getEnderecoImovel() != null) {
                this.imovelMerge.getImAlteracao().getEnderecoImovel().setAtivo(false);
            }

            //Endereco Correspondencia Imóvel
            if (this.imovelMerge.getEndCorrespIncluido() != null && this.imovelMerge.getUsarEndCorrespIncluido()) {
                Endereco e = this.imovelMerge.getEndCorrespIncluido().getClone();
                e.setId(null);
                e = (Endereco) MergeUtilitario.setCamposNulos(e);
                e.setImovel(this.imovelMerge.getImInclusao());
                this.enderecoServico.save(e);
                this.imovelMerge.getImInclusao().setEnderecoCorrespondencia(e);
            } else if (this.imovelMerge.getcEnderecoCorresp() != null) {
                //Campos Endereco Correspondencia
                for (Campo<?> campo : this.imovelMerge.getcEnderecoCorresp()) {
                    if (campo.getUsarAlteracao()) {
                        MergeUtilitario.setPrivateField(this.imovelMerge.getImInclusao().getEnderecoCorrespondencia(), campo.getField(), campo.getVlrAlteracao());
                    }
                }
            }
            if (this.imovelMerge.getImAlteracao().getEnderecoCorrespondencia() != null) {
                this.imovelMerge.getImAlteracao().getEnderecoCorrespondencia().setAtivo(false);
            }

            //Anexos
            if (this.imovelMerge.getImInclusao().getAnnex() == null && !this.imovelMerge.getAnexosIncluidos().isEmpty()) {
                this.imovelMerge.getImInclusao().setAnnex(new ArrayList<Anexo>());
            }
            for (Campo<Anexo> cp : this.imovelMerge.getAnexosIncluidos()) {
                if (cp.getUsarAlteracao()) {
                    Anexo a = MergeUtilitario.copiaAnexo(cp.getVlrAlteracao());

                    File original = new File(a.getUrl() + a.getNome());
                    a.setArquivo(MergeUtilitario.getBytes(original));

                    arquivoUtilitario.gravarAnexoCopia(a);

                    a.setId(null);
                    a = (Anexo) MergeUtilitario.setCamposNulos(a);
                    a.setImovel(this.imovelMerge.getImInclusao());
                    this.arquivoUtilitario.removerBytes(a);
                    this.anexoServico.save(a);
                    this.imovelMerge.getImInclusao().getAnnex().add(a);
                }
            }

            this.imovelMerge.getImAlteracao().setProprietarios(this.imovelServico.lstProprietario(this.imovelMerge.getImAlteracao()));
            for (Proprietario proprietario : this.imovelMerge.getImAlteracao().getProprietarios()) {
                this.updateProprietario(MergeUtilitario.setProprietarioInativo(proprietario));
            }

            //Proprietarios incluidos
            if (this.imovelMerge.getImInclusao().getProprietarios() == null && !this.imovelMerge.getProprietariosIncluidos().isEmpty()) {
                this.imovelMerge.getImInclusao().setProprietarios(new ArrayList<Proprietario>());
            }
            for (Campo<Proprietario> cp : this.imovelMerge.getProprietariosIncluidos()) {
                if (cp.getUsarAlteracao()) {
                    Proprietario p = MergeUtilitario.cloneProprietario(cp.getVlrAlteracao(), false);
                    p = saveProprietario(p);
                    p = this.proprietarioServico.find(p.getId());
                    this.imovelMerge.getImInclusao().getProprietarios().add(p);
                }
            }

            if (this.imovelMerge.getImInclusao().getPagaIptu() != null) {
                this.imovelMerge.getImInclusao().setIsentoIptu(!this.imovelMerge.getImInclusao().getPagaIptu());
            }
            this.imovelServico.update(this.imovelMerge.getImInclusao());
            this.imovelMerge.setImInclusao(this.imovelServico.find(this.imovelMerge.getImInclusao().getId()));
            this.imovelMerge.getImInclusao().setProprietarios(this.imovelServico.lstProprietario(this.imovelMerge.getImInclusao()));

//        //Proprietários com mesmo documento
            for (ProprietarioMerge pm : this.imovelMerge.getProprietariosMerge()) {
                if (pm.getTemDiferenca()) {
                    pm = MergeUtilitario.mergeProprietario(pm, false);
                    updateProprietario(pm.getPropInclusao());
                }
            }

            this.imovelServico.update(this.imovelMerge.getImInclusao());

            this.imovelMerge.getImAlteracao().setAtivo(Boolean.FALSE);
            this.imovelServico.update(this.imovelMerge.getImAlteracao());

        } catch (Exception e) {
            Msg.messagemError("Ocorreu um erro!");
        }
        Msg.messagemInfo("Imóvel Atualizado");
        init();
    }

    public String exibir(Object valor, Class aClass) {
        if (aClass.equals(Boolean.class)) {
            return Boolean.valueOf(valor.toString()) ? "Sim" : "Não";
        } else if (aClass.equals(String.class)) {
            return valor.toString();
        } else if (aClass.equals(BigDecimal.class)) {
            DecimalFormat df = new DecimalFormat("#,##0.00");
            return df.format(valor);
        } else if (aClass.equals(Date.class)) {
            return new SimpleDateFormat("dd/MM/yyyy").format(valor);
        } else if (aClass.equals(Bairro.class)) {
            return ((Bairro) valor).getNome();
        } else {
            return valor.toString();
        }
    }

    public boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public ImovelMerge getImovelMerge() {
        return imovelMerge;
    }

    public void setImovelMerge(ImovelMerge im) {
        this.imovelMerge = im;
    }

    private Proprietario saveProprietario(Proprietario p) {
        if (p.getConjuge() != null) {
            if (p.getConjuge().getAnexos() != null) {
                for (Anexo anexo : p.getConjuge().getAnexos()) {
                    this.arquivoUtilitario.removerBytes(anexo);
                    this.anexoServico.save(anexo);
                }
            }
            this.proprietarioServico.salvar(p.getConjuge());
        }

        if (p.getAnexos() != null) {
            for (Anexo anexo : p.getAnexos()) {
                this.arquivoUtilitario.removerBytes(anexo);
                this.anexoServico.save(anexo);
            }
        }

        this.proprietarioServico.salvar(p);
        return p;
    }

    private Proprietario updateProprietario(Proprietario p) {
        if (p.getConjuge() != null) {
            if (p.getConjuge().getAnexos() != null) {
                for (Anexo anexo : p.getConjuge().getAnexos()) {
                    this.arquivoUtilitario.removerBytes(anexo);
                    this.anexoServico.save(anexo);
                }
            }
            if (p.getConjuge().getId() != null) {
                if (p.getConjuge().getEndereco() != null) {
                    if (p.getConjuge().getEndereco().getId() == null) {
                        this.enderecoServico.save(p.getConjuge().getEndereco());
                    }
                }
                this.proprietarioServico.update(p.getConjuge());
            } else {
                this.proprietarioServico.salvar(p.getConjuge());
            }
            p.setConjuge(this.proprietarioServico.find(p.getConjuge().getId()));
        }

        if (p.getAnexos() != null) {
            for (Anexo anexo : p.getAnexos()) {
                this.arquivoUtilitario.removerBytes(anexo);
                this.anexoServico.save(anexo);
            }
        }

        if (p.getId() != null) {
            if (p.getEndereco() != null) {
                if (p.getEndereco().getId() == null) {
                    this.enderecoServico.save(p.getEndereco());
                }
            }
            this.proprietarioServico.update(p);
        } else {
            this.proprietarioServico.salvar(p);
        }
        if (p.getConjuge() != null) {
            p = this.proprietarioServico.find(p.getId());
            p.getConjuge().setConjuge(p);
            this.proprietarioServico.update(p.getConjuge());
        }

        return p;
    }

    public String inscricaoCadastral(Imovel visaoImovel) {
        String visaoInscricao = "";
        DecimalFormat d = new DecimalFormat("");
        d.setMinimumIntegerDigits(2);
        visaoInscricao += d.format(visaoImovel.getInscricaoCadastralD() == null ? 0 : visaoImovel.getInscricaoCadastralD());
        visaoInscricao += ".";
        visaoInscricao += d.format(visaoImovel.getInscricaoCadastralS() == null ? 0 : visaoImovel.getInscricaoCadastralS());
        visaoInscricao += ".";
        d.setMinimumIntegerDigits(3);
        visaoInscricao += d.format(visaoImovel.getInscricaoCadastralQuadra() == null ? 0 : visaoImovel.getInscricaoCadastralQuadra());
        visaoInscricao += ".";
        d.setMinimumIntegerDigits(4);
        d.setDecimalSeparatorAlwaysShown(true);
        visaoInscricao += d.format(visaoImovel.getInscricaoCadastralLote() == null ? 0 : visaoImovel.getInscricaoCadastralLote()).replace(".", "");
        visaoInscricao += ".";
        d.setMinimumIntegerDigits(2);
        visaoInscricao += d.format(visaoImovel.getInscricaoCadastralUnid() == null ? 0 : visaoImovel.getInscricaoCadastralUnid());
        visaoInscricao = visaoInscricao.replace(",", "");
        return visaoInscricao;
    }

    public void voltar() {
        try {
            String url = "pesquisarimovel.xhtml?inscricaoimovel=" + this.inscImovel + "&vReg=true";
            FacesContext.getCurrentInstance().getExternalContext().redirect(url);
        } catch (IOException ex) {
            Logger.getLogger(ManagerAtualizarImovel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
